import {
    Component,
    OnInit,
    Injector,
    ViewChild,
    Output,
    EventEmitter,
    ElementRef,
    Input,
    ViewEncapsulation
} from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import {
    StockZT_OutBillItemServiceProxy,
    ListDtoExtensionsItem,
    ComboboxItemDto,
    StockZT_AccountBaseServiceProxy,
    StockType,
    Stock_AccountBaseListDto,
    StockZT_RoomServiceProxy,
    StockZT_IntoBillItemServiceProxy
} from '@shared/service-proxies/stock-service-proxies';
import { ModalDirective } from 'ngx-bootstrap';
import { finalize } from 'rxjs/operators';
import { LazyLoadEvent } from 'primeng/api';
import { Paginator } from 'primeng/primeng';
import { Table } from 'primeng/table';
import { appModuleAnimation } from '@shared/animations/routerTransition';
// import {
//     CostZT_ProdQCCardServiceProxy,
//     Cost_ProdQCCardListDto,
//     ListResultDtoOfBomDto
// } from '@shared/service-proxies/stock-service-proxies';
import { UserDataPermissionServiceProxy } from '@shared/service-proxies/stock-service-proxies';
import * as _ from 'lodash';

@Component({
    selector: 'simpleAccountBaseInfoModal',
    templateUrl: './account-base-info-modal.component.html',
    styleUrls: ['./account-base-info-modal.component.less'],
    animations: [appModuleAnimation()],
    encapsulation: ViewEncapsulation.None
})
export class SimpleAccountBaseInfoModalComponent extends AppComponentBase implements OnInit {
    constructor(
        injector: Injector,
        //private _costZT_TaskServiceProxy: CostZT_ProdQCCardServiceProxy,
        private _accountService: StockZT_AccountBaseServiceProxy,
        private _userDataPermissionServiceProxy: UserDataPermissionServiceProxy,
        private _stockZT_RoomServiceProxy: StockZT_RoomServiceProxy,
        private _billService: StockZT_IntoBillItemServiceProxy
    ) {
        super(injector);
    }
    @Input() set stocktype(val) {
        if (val) {
            this._type = val;
        }
    }
    @Input() set handletype(val) {
        if (val) {
            this._handletype = val;
        }
    }

    @ViewChild('createOrEditModal') modal: ModalDirective;
    @ViewChild('createOrEditModal') modalEl: ElementRef;
    @ViewChild('paginator') paginator: Paginator;
    @ViewChild('dataTable') dataTable: Table;
    _type: StockType;
    _handletype: string;
    anyncing = false;
    filterText = '';
    qccardFilter = '';
    f_MaterialCode = '';
    f_MaterialName = '';
    f_TradeMark = '';
    f_Station = '';
    f_TecCondition = '';
    f_Specification = '';
    f_certificateNum = '';
    f_zydh = '';
    f_recheckNum = '';
    userDataPermissions;
    selectedDepts = new ComboboxItemDto();
    //qccardInfo = new Cost_ProdQCCardListDto();
    selectedValue: Array<Stock_AccountBaseListDto>;
    extensions: Array<ListDtoExtensionsItem>;
    useableOptions = [{ label: '可用', value: true }, { label: '全部', value: undefined }];
    isuseable;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();
    @Output() qccard: EventEmitter<any> = new EventEmitter<any>();
    @Output() clearSelectedValue: EventEmitter<any> = new EventEmitter<any>();

    // active = false;
    saving = false;
    closed = false;
    billId = '';
    isShown = false;
    purchasetype;
    selectedWareHouse = new Array<ComboboxItemDto>();
    selectedPurchase = new Array<ComboboxItemDto>();
    roomOption;
    ngOnInit(): void {
        this._userDataPermissionServiceProxy.getUserDataPermissions('Mili_Accounts').subscribe(result => {
            this.userDataPermissions = result.items.map(e => {
                return {
                    label: e.displayText,
                    value: e
                };
            });
            if (this.userDataPermissions.length > 0) {
                if (this._type.toString() == '工具') {
                    //2019-09-17 kf8
                    //this.selectedDepts = this.userDataPermissions[41].value;
                } else {
                    this.selectedDepts = this.userDataPermissions[0].value;
                }
                this.getRecordsIfNeeds();
            }
        });
        if (this._type.toString() == '市采' && this._handletype.toString() !="退库") {
            this._userDataPermissionServiceProxy.getUserDataPermissions('Warehouses').subscribe(result => {
                this._stockZT_RoomServiceProxy.getLevelOneRoomListByStockType('市采物资库').subscribe(result2 => {
                    this.roomOption = result2.items.map(e => {
                        return {
                            label: e.displayText,
                            value: e
                        };
                    });
                    this.selectedWareHouse = result2.items;
                });
            });
        }
        if(this._type.toString() == '市采' && this._handletype.toString() =="退库"){
            this._userDataPermissionServiceProxy.getUserDataPermissions('Warehouses').subscribe(result => {
                this._stockZT_RoomServiceProxy
                    .getRoomListByDepts(result.items, "市采物资库", this._handletype)
                    .subscribe(result2 => {
                        this.roomOption = result2.items.map(e => {
                            return {
                                label: e.displayText,
                                value: e
                            };
                        });
                        this.selectedWareHouse = result2.items;
                    });
            });
        }
        if (this._type.toString() == '工具') {
            this._userDataPermissionServiceProxy.getUserDataPermissions('Warehouses').subscribe(result => {
                this._stockZT_RoomServiceProxy
                    .getRoomListByDepts(result.items, '工具库', this._handletype)
                    .subscribe(result2 => {
                        this.roomOption = result2.items.map(e => {
                            return {
                                label: e.displayText,
                                value: e
                            };
                        });
                        this.selectedWareHouse = result2.items;
                    });
            });
        }
        if (this._type.toString() == '军品') {
            this._userDataPermissionServiceProxy.getUserDataPermissions('Warehouses').subscribe(result => {
                this._stockZT_RoomServiceProxy
                    .getRoomListByDepts(result.items, '原材料库', this._handletype)
                    .subscribe(result2 => {
                        this.roomOption = result2.items.map(e => {
                            return {
                                label: e.displayText,
                                value: e
                            };
                        });
                        this.selectedWareHouse = result2.items;
                    });
            });
        }
    }
    show(billid?: string, purchasetype?: string): void {
        //  this.active = true;
        this.closed = false;
        this.billId = billid;
        this.purchasetype = purchasetype;
        if (purchasetype) {
            this.selectedPurchase = new Array<ComboboxItemDto>();
            let t = new ComboboxItemDto();
            t.displayText = this.purchasetype;
            t.value = this.purchasetype;
            this.selectedPurchase.push(t);
        }
        this.isuseable = true;
        this.modal.show();
        this.getBaseAccount();
    }

    shown(): void {
        this.isShown = true;
        this.getRecordsIfNeeds(null);
    }

    getRecordsIfNeeds(event?: LazyLoadEvent): void {
        if (!this.isShown) {
            return;
        }
        this.getBaseAccount(event);
    }
    clearQuery() {
        this.filterText = '';
        this.qccardFilter = '';
        this.f_MaterialCode = '';
        this.f_MaterialName = '';
        this.f_TradeMark = '';
        this.f_Station = '';
        this.f_TecCondition = '';
        this.f_Specification = '';
        this.f_certificateNum = '';
        this.f_zydh = '';
        this.f_recheckNum = '';
        this.selectedWareHouse;
        this.userDataPermissions;
    }
    close(): void {
        //  this.active = false;
        this.isShown= false;
        this.modal.hide();
    }
    cancel():void{
        this.clearSelectedValue.emit();
        this.close();
    }

    onHidden(event) {
        this.closed = true;
    }

    save() {
        this.modalSave.emit(this.selectedValue);
        this.selectedValue = null;
        this.clearQuery();
        this.close();
    }
    commit() {
        console.log(this._handletype);

        if (this._handletype == '出库') {
            // this._costZT_TaskServiceProxy.getProdQccardByQccardNum(this.qccardFilter).subscribe(result => {
            //     if (result.f_QCCardNum == null || result.f_QCCardNum == undefined) {
            //         this.notify.error('质控卡号不存在');
            //         this.qccardFilter = '';
            //         return;
            //     }
            //     //this.qccardInfo = result;
            //     this.qccard.emit(result);
            //     this.modalSave.emit(this.selectedValue);
            //     this.qccardFilter = '';
            // });
        } else {
            this.modalSave.emit(this.selectedValue);
        }
    }
    getBaseAccount(event?: LazyLoadEvent) {       
        if(event==undefined && this._type.toString() == '市采' && this._handletype.toString() == '退库'){
            this.selectedValue = new Array<Stock_AccountBaseListDto>();
        }
        if (this.primengTableHelper.shouldResetPaging(event) || event.first == undefined) {
            this.paginator.changePage(0);

            return;
        }

        if (this._type.toString() == '市采' && this.selectedWareHouse.length < 1) {
            return;
        }
        if (
            this._type.toString() == '市采' &&
            this._handletype.toString() == '出库' &&
            this.selectedPurchase.length < 1
        ) {
            return;
        }
        this.primengTableHelper.showLoadingIndicator();

        this._accountService
            .getAccountListExtension(
                undefined,
                this.f_MaterialCode,
                this.f_MaterialName,
                this.f_TradeMark,
                this.f_Station,
                this.f_TecCondition,
                this.f_Specification,
                undefined,
                this.selectedWareHouse,
                this.f_recheckNum,
                this.f_certificateNum,
                this.f_zydh,
                undefined,
                undefined,
                undefined,
                this.isuseable,
                this._type,
                this.selectedPurchase,
                this._handletype,
                undefined,

                this.primengTableHelper.getMaxResultCount(this.paginator, event),
                this.primengTableHelper.getSkipCount(this.paginator, event)
            )
            .subscribe(result => {
                this.extensions = result.items;
                this.primengTableHelper.totalRecordsCount = result.stock_AccountBaseListDto.totalCount;
                this.primengTableHelper.records = result.stock_AccountBaseListDto.items;
                this.primengTableHelper.hideLoadingIndicator();
            });
    }
}
